import { saveCuesActive } from '@/services/api/api-cues-active';
import { getCuesIndustry } from '@/services/api/api-cues-industry';
import { PlusOutlined } from '@ant-design/icons';

import ProForm, {
  DrawerForm,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { ActionType } from '@ant-design/pro-table';
import { Button, message } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import 'dayjs/locale/zh-cn';
import React, { useRef, useState } from 'react';
import TextEditor from '../../components/TextEditor';
import UploadDragger from '../../components/UploadDragger';
import TagGroup from '@/components/TagGroup';

interface AddActiveProps {
  onRefurbish: () => void;
}

const AddActive: React.FC<AddActiveProps> = ({ onRefurbish }) => {
  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();

  const [industrys, setIndustrysState] = useState<any[]>([]);

  /**
   * 加载权限详情
   * @param key
   */
  const getCuesIndustryData = async () => {
    try {
      const response = await getCuesIndustry();

      setIndustrysState(
        response.data.map((item) => {
          return { label: item.name, value: item.id };
        }),
      );
    } catch (error) { }
  };

  return (
    <DrawerForm
      key="add_active_drawer_form"
      title="主动报送"
      drawerProps={{
        maskClosable: false,
        destroyOnClose: true,
      }}
      formRef={formRef}
      trigger={
        <Button key="create" type="primary">
          <PlusOutlined />
          主动报送
        </Button>
      }
      initialValues={{
        isDemandClipboard: 1,
      }}
      onVisibleChange={(visible) => {
        if (visible) {
          getCuesIndustryData();
        }
      }}
      onFinish={async (values) => {
        if (values.articleAttachments !== undefined && values.articleAttachments.length > 0) {
          let articleAttachments = values.articleAttachments.map(
            (item: { response: { data: { id: any } } }) => {
              return item.response.data.id;
            },
          );

          values.articleAttachments = articleAttachments;
        }

        const response = await saveCuesActive({
          ...values,
        });

        if (response.code === 0) {
          message.success('提交成功');
          onRefurbish();
          return true;
        } else {
          return false;
        }
      }}
    >
      <ProForm.Group>
        <ProFormText
          width="xl"
          name="articleName"
          label="标题"
          rules={[{ required: true, message: '请输入标题' }]}
          fieldProps={{
            allowClear: true,
            maxLength: 200,
          }}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect
          name="articleIndustry"
          label="行业（单选）"
          width="xl"
          showSearch
          fieldProps={{
            // mode: 'multiple',
            allowClear: true,
            showSearch: true,
            optionFilterProp: 'children',
            filterOption: (input: any, option: any) => {
              console.log(option);
              // return option.options.filter((item: any) => item.label.includes(input));
              return option.label.includes(input);
            },
            listHeight: 500,
          }}
          rules={[{ required: true, message: '请选择至少一个行业' }]}
          options={industrys}
        />
      </ProForm.Group>
      <ProForm.Group>
        {/* <ProFormSelect
          name="articleLabels"
          label="标签（输入后，点击空白处/按下回车键可新增标签）"
          width="xl"
          placeholder="请输入"
          fieldProps={{
            mode: 'tags',
            allowClear: true,
            open: false,
          }}
          rules={[
            {
              required: true,
              validator: (rule, value, callback) => {
                if (value === undefined) {
                  return callback('用于描述选题特点，至少填写一个');
                }

                if (value !== undefined && value.length < 1) {
                  return callback('用于描述选题特点，至少填写一个');
                }

                return Promise.resolve();
              },
            },
            {
              required: true,
              validator: (rule, value, callback) => {
                if (value !== undefined) {
                  const re = new RegExp('^[\u4E00-\u9FA5A-Za-z0-9]+$');
                  for (const elem of value) {
                    if (re.test(elem)) {
                    } else {
                      return callback('只能输入汉字、英文字母和数字');
                    }
                  }
                }
                return Promise.resolve();
              },
            },
          ]}
        /> */}
        <FormItem
          label={
            <>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              标签
            </>
          }
          name="articleLabels"
          extra={'最少输入一个'}
        >
          <TagGroup />
        </FormItem>
      </ProForm.Group>
      <ProForm.Group>
        <ProFormTextArea
          name="remarks"
          label="备注"
          width="xl"
          fieldProps={{
            allowClear: true,
            rows: 3,
            maxLength: 200,
          }}
        />
      </ProForm.Group>
      <FormItem
        name="articleContent"
        label="正文"
        rules={[{ required: true, message: '请输入正文' }]}
      >
        <TextEditor
          onInit={(editor) => { }}
          readonly={false}
          onClick={(value) => { }}
          defaultContent=""
        />
      </FormItem>

      <FormItem name="articleAttachments" label="附件">
        <UploadDragger onPreview={(file) => { }} />
      </FormItem>
    </DrawerForm>
  );
};
export default AddActive;
